package com.example.backend.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.lang.NonNull;

import java.util.Arrays;

/**
 * 缓存配置类 - 性能优化版
 * 提供高性能的内存缓存支持，优化工单查询性能
 */
@Configuration
@EnableCaching
@ConditionalOnProperty(name = "spring.cache.type", havingValue = "simple", matchIfMissing = true)
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
        // 定义缓存区域
        cacheManager.setCacheNames(Arrays.asList(
            "tickets",           // 工单缓存
            "tickets_list",      // 工单列表缓存
            "tickets_search",    // 工单搜索缓存
            "tickets_stats",     // 工单统计缓存
            "users",             // 用户缓存
            "users_list",        // 用户列表缓存
            "feedbacks",         // 反馈缓存
            "comments",          // 评论缓存
            "categories",        // 分类缓存
            "tags",              // 标签缓存
            "permissions",       // 权限缓存
            "system_settings"    // 系统设置缓存
        ));
        
        // 启用缓存空值，避免缓存穿透
        cacheManager.setAllowNullValues(true);
        
        return cacheManager;
    }

    @Bean
    public KeyGenerator ticketKeyGenerator() {
        return new TicketKeyGenerator();
    }

    @Bean
    public KeyGenerator userKeyGenerator() {
        return new UserKeyGenerator();
    }

    /**
     * 自定义工单缓存键生成器
     * 优化缓存键的生成策略，提高缓存命中率
     */
    public static class TicketKeyGenerator implements KeyGenerator {
        @Override
        @NonNull
        public Object generate(@NonNull Object target, @NonNull java.lang.reflect.Method method, @NonNull Object... params) {
            StringBuilder keyBuilder = new StringBuilder();
            keyBuilder.append(target.getClass().getSimpleName())
                     .append(".")
                     .append(method.getName());
            
            if (params != null && params.length > 0) {
                keyBuilder.append(":");
                for (Object param : params) {
                    if (param != null) {
                        keyBuilder.append(param.toString()).append("_");
                    }
                }
            }
            
            return keyBuilder.toString();
        }
    }

    /**
     * 自定义用户缓存键生成器
     */
    public static class UserKeyGenerator implements KeyGenerator {
        @Override
        @NonNull
        public Object generate(@NonNull Object target, @NonNull java.lang.reflect.Method method, @NonNull Object... params) {
            StringBuilder keyBuilder = new StringBuilder();
            keyBuilder.append("user_")
                     .append(target.getClass().getSimpleName())
                     .append(".")
                     .append(method.getName());
            
            if (params != null && params.length > 0) {
                keyBuilder.append(":");
                for (Object param : params) {
                    if (param != null) {
                        keyBuilder.append(param.toString()).append("_");
                    }
                }
            }
            
            return keyBuilder.toString();
        }
    }
}
